import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

let hasUrl = (path: String, next: Function) => {
  // 判断本地信息权限列表中是否包含该权限
  let flag = JSON.parse(sessionStorage.getItem('userInfo') + '').menus_url.some(
    (item: String) => item == path
  )
  if (flag) {
    // 如果有下一步
    next()
  } else {
    // 如果没有，则去首页
    next('/home')
  }
}
const routes: Array<RouteRecordRaw> = [
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue')
      },
      {
        path: '/menu',
        component: () => import('../views/menu/menu.vue'),
        name: '菜单管理',
        // 路由独享守卫
        beforeEnter (to, from, next) {
          // 调用分装好的函数
          hasUrl('/menu', next)
        }
      },
      {
        path: '/role',
        component: () => import('../views/role/role.vue'),
        name: '角色管理',
        beforeEnter (to, from, next) {
          // 调用分装好的函数
          hasUrl('/role', next)
        }
      },
      {
        path: '/user',
        component: () => import('../views/user/user.vue'),
        name: '管理员管理',
        beforeEnter (to, from, next) {
          // 调用分装好的函数
          hasUrl('/user', next)
        }
      },
      {
        path: '',
        redirect: '/home'
      }
    ]
  },
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/',
    redirect: '/index'
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
// 全局导航拦截
router.beforeEach((to, from, next) => {
  // 判断来源是否去登录
  if (to.path == '/login') {
    next()
    return
  }
  // 判断是否登录过
  if (sessionStorage.getItem('userInfo')) {
    next()
    return
  }
  // 否则则未登录,跳转到登录
  next('/login')
})
export default router
